package cn.b.training.baby_education_training.security;

import cn.b.training.baby_education_training.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtApiFilter extends GenericFilterBean {
    @Autowired
    TokenService tokenService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、从请求头部找到令牌
        String token=request.getHeader("Authorization");
        if(token==null){//如果请求头部没有，从查询参数中找到令牌
            token=request.getParameter("Authorization");
        }
        if(token!=null){
            if(token.startsWith("Bearer ")){
                token=token.replace("Bearer ","");
            }
            try{
                //通过令牌返解析出令牌用户对象。
                //返解析过程中jwt工具类会校验格式、校验有效期。
                UserInfo userToken= this.tokenService.getUser(token);
                if(userToken!=null){
                    //根据用户角色数组，创建security所需的权限列表authorities。
                    List<SimpleGrantedAuthority> authorities=new ArrayList<>();
                    SimpleGrantedAuthority authority=new SimpleGrantedAuthority("role_user");
                    authorities.add(authority);
                    //构造为UserDetailsService用户对象
                    User authenticatedUser=new User(userToken.getPhone(),"",authorities);
                    //构造一个SpringSecurity授权对象Authentication
                    //授权对象Authentication需包含3个要素：
                    //1、用户对象：此处直接使用UserDetailsService用户对象
                    //2、用户令牌：当前令牌
                    //3、用户权限：至少赋予一个权限才能够被SpringSecurity视为已认证。
                    Authentication user=new UsernamePasswordAuthenticationToken(authenticatedUser,token,authorities);
                    //将授权对象交给SpringSecurity管理。
                    SecurityContextHolder.getContext().setAuthentication(user);
                }

            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
